package cn.tedu.csmall.product.ex.handler;

import cn.tedu.csmall.product.ex.ServiceException;
import cn.tedu.csmall.product.web.JsonResult;
import cn.tedu.csmall.product.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Set;
import java.util.StringJoiner;

/**
 * 全局异常处理器
 *
 * 通常将统一异常的代码定义在专门的类中,并在此类上添加@RestControllerAdvice注解,
 * 添加了此注解的类中的特定方法将作用于整个项目任何处理请求的方法的过程
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    public GlobalExceptionHandler(){
        log.debug("创建全局异常处理对象:GlobalExceptionHandler");
    }

    @ExceptionHandler
    public JsonResult HandleServiceException(ServiceException e){
        log.debug("处理请求的方法抛出了ServiceException,将统一处理");
        return JsonResult.fail(e);
    }

    @ExceptionHandler
    public JsonResult handle(BindException e){
        log.debug("开始处理BindException");

        String defaultMessage = e.getFieldError().getDefaultMessage();

//        StringJoiner stringJoiner = new StringJoiner(",","请求参数格式错误:","!!!");
//        List<FieldError> fieldErrors = e.getFieldErrors();
//        for(FieldError fieldError : fieldErrors){
//            String defaultMessage = fieldError.getDefaultMessage();
//            stringJoiner.add(defaultMessage);
//        }
        return JsonResult.fail(ServiceCode.ERR_BAD_REQUEST, defaultMessage);
    }

    @ExceptionHandler
    public JsonResult handle(ConstraintViolationException e){
        log.debug("开始处理ConstraintViolationException");
        StringJoiner stringJoiner = new StringJoiner(",");
        Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations();
        for (ConstraintViolation<?> constraintViolation : constraintViolations){
            stringJoiner.add(constraintViolation.getMessage());
        }
        return JsonResult.fail(ServiceCode.ERR_BAD_REQUEST, stringJoiner.toString());
    }

    @ExceptionHandler
    public JsonResult<Void> handleAccessDeniedException(AccessDeniedException e) {
        log.debug("捕获到AccessDeniedException");
        String message = "访问失败，当前登录的用户不具有此操作权限！";
        return JsonResult.fail(ServiceCode.ERR_FORBIDDEN, message);
    }

    @ExceptionHandler
    public String handleThrowable(Throwable e) {
        String message = "你有异常没有处理，请根据服务器端控制台的信息，补充对此类异常的处理！！！";
        e.printStackTrace();
        return message;
    }
}